package com.zhihuichongcheng.application.ui.task;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.smartlib.cmnObject.util.DialogUtil;
import com.smartlib.cmnObject.util.GsonUtil;
import com.smartlib.cmnObject.util.StringUtil;
import com.smartlib.cmnObject.util.ToastOpt;
import com.zhihuichongcheng.application.R;
import com.zhihuichongcheng.application.base.BaseActivity;
import com.zhihuichongcheng.application.bean.task.SubTaskBean;
import com.zhihuichongcheng.application.constant.NetworkAPI;
import com.zhihuichongcheng.application.net.HttpCallback;
import com.zhihuichongcheng.application.net.HttpManager;
import com.zhihuichongcheng.application.ui.task.adapter.SubTaskAdapter;
import com.zhihuichongcheng.application.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;

/**
 * subTask Created by LK on 2017/1/17.
 */

public class SubTaskListActivity extends BaseActivity
        implements View.OnClickListener {
    public static final String ACTION_REFRESH_SUB_LIST = "intent.refresh.sub.task.list";
    public static final String EXTRA_TASK_ID = "extra_task_id";
    public static final String EXTRA_TASK_TO_USER_IDS = "extra_task_to_user_ids";
    protected Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            }
        }
    };
    protected HttpManager manager;
    private XRecyclerView mRecyclerView;
    private SubTaskAdapter mAdapter;
    private IntentFilter intentFilter;
    private SubTaskReceiver receiver;

    private int currentTaskId;
    private String toUserIds;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (null != getIntent().getExtras()) {
            Bundle bundle = getIntent().getExtras();
            if (bundle.containsKey(EXTRA_TASK_ID))
                currentTaskId = bundle.getInt(EXTRA_TASK_ID);
            if (bundle.containsKey(EXTRA_TASK_TO_USER_IDS))
                toUserIds = bundle.getString(EXTRA_TASK_TO_USER_IDS);
        }

        setContentView(R.layout.activity_sub_task_list);
        manager = HttpManager.getInstance(this);
        registerReceiver();
        initView();
        initListView();

        loadData();
    }

    public void registerReceiver() {
        intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_REFRESH_SUB_LIST);

        receiver = new SubTaskReceiver();
        registerReceiver(receiver, intentFilter);
    }

    private void initView() {
        setTitle("子任务");
        getTvArrowTitle().setVisibility(View.INVISIBLE);
        if (currentUserIsReceiveUser()) {
            setImRight(R.drawable.ic_add_msg, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Bundle bundle = new Bundle();
                    bundle.putInt(SubTaskDetailActivity.EXTRA_TASK_ID, currentTaskId);
                    startActivity(SubTaskDetailActivity.class, bundle);
                }
            });
        }

        mRecyclerView = (XRecyclerView) this.findViewById(R.id.rv_sub_task);
        mRecyclerView.setHasFixedSize(true);
    }

    private void initListView() {
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(manager);

        mAdapter = new SubTaskAdapter(this);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setLoadingMoreEnabled(false);

        //Header
        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadData();
            }

            @Override
            public void onLoadMore() {
            }
        });
    }

    private void loadData() {
        DialogUtil.showLoadDiadlog(mContext);
        HashMap<String, String> paramsDemo = new HashMap<>();
        paramsDemo.put("token", mUser.getToken());
        paramsDemo.put("userMissionId", currentTaskId + "");
        manager.post(NetworkAPI.MISSION_SUBTASK_LIST, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {
                DialogUtil.dismiss(getContext());
                if (code == 2) {
                    ToastOpt.createToast(getContext(), msg);
                    return;
                }
                List<SubTaskBean> taskList = GsonUtil.paraeFromStringToList(value, SubTaskBean.class);
                mAdapter.reSetData(taskList);
                mAdapter.notifyDataSetChanged();
                mRecyclerView.refreshComplete();
                mRecyclerView.loadMoreComplete();
            }

            @Override
            public void onFailure(String value) {
                ToastOpt.createToast(getContext(), "查询失败 " + value);
                DialogUtil.dismiss(getContext());
                mRecyclerView.refreshComplete();
                mRecyclerView.loadMoreComplete();
            }
        }, paramsDemo);
    }

    /**
     * 当前用户是任务执行者
     */
    private boolean currentUserIsReceiveUser() {
        final boolean[] result = {false};
        final String currentUserId = app.getUser().getUserId();
        String[] receiveUsers = toUserIds.split(",");
        CollectionUtils.iterator(receiveUsers, new CollectionUtils.AIIteratorListCallBack() {
            @Override
            public boolean callback(Object data, int position) {
                String itemUserId = data.toString();
                if (!StringUtil.isEmpty(itemUserId) && itemUserId.equals(currentUserId)) {
                    result[0] = true;
                    return true;
                }
                return false;
            }
        });

        return result[0];
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver();
    }

    public void unregisterReceiver() {
        if (null != receiver) {
            unregisterReceiver(receiver);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        }
    }

    class SubTaskReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ACTION_REFRESH_SUB_LIST)) {
                loadData();
            }
        }
    }
}
